package cn.tftech.hudchartssw.request;

import android.database.Cursor;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;

/**
 * @author:zhangshihao
 * @date:2019-07-11
 * @description:
 */
public class LocalDataSource {

    private static LocalDataSource mLocalDataSource;

    private static String sql = "select * from v_data_flier";

    public static LocalDataSource getInstance() {
        if (mLocalDataSource == null) {
            synchronized (LocalDataSource.class) {
                if (mLocalDataSource == null) {
                    mLocalDataSource = new LocalDataSource();
                }
            }
        }
        return mLocalDataSource;
    }

    public Observable<List<HudBean>> getHudData() {
        return Observable.create(emitter -> {
            List<HudBean> hudBeans = new ArrayList<>();

            Cursor cursor = SqlCollection.getInstance().getDatabase().rawQuery(sql, null);

            while (cursor.moveToNext()) {
                hudBeans.add(getHudBean(cursor));
            }

            emitter.onNext(hudBeans);
            emitter.onComplete();
        });
    }

    private HudBean getHudBean(Cursor cursor) {

        HudBean hudBean = new HudBean();

        hudBean.setKeyId(parameterString(cursor, "keyid"));
        hudBean.setKeyType(parameterString(cursor, "keytype"));
        hudBean.setKeyTitle(parameterString(cursor, "keytitle"));
        hudBean.setKeyName(parameterString(cursor, "keyname"));
        hudBean.setKeyValue(parameterString(cursor, "keyvalue"));
        hudBean.setKeyView(parameterString(cursor, "keyview"));
        hudBean.setKeyOrder(parameterString(cursor, "keyorder"));

        return hudBean;
    }

    private String parameterString(Cursor cursor, String columnIndex) {
        return cursor.getString(cursor.getColumnIndex(columnIndex));
    }

}
